package com.epic.network;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.os.AsyncTask;
import android.util.Log;

import com.epic.item.MediaItem;
import com.epic.item.ResponseItem;
import com.google.gson.Gson;

public class EpicLoader extends AsyncTask<Void, String, Integer> {
	private String url = "http://epic.vn/api/bathu.php?limit=10&start=";
	private static int start = 0;
	private final static int ERROR = -1;
	private final static int OK = 1;
	private OnReceiverDataListener listener;
	List<MediaItem> datas = new ArrayList<MediaItem>();
	private OnRequestMediaListener onRequestMediaListener;

	public EpicLoader(OnReceiverDataListener listener,
			OnRequestMediaListener onRequestMediaListener) {
		this.listener = listener;
		this.onRequestMediaListener = onRequestMediaListener;
	}

	@Override
	protected Integer doInBackground(Void... params) {
		url = url + start;
		DefaultHttpClient client = new DefaultHttpClient();
		HttpGet getRequest = new HttpGet(url);
		try {
			HttpResponse getResponse = client.execute(getRequest);
			final int statusCode = getResponse.getStatusLine().getStatusCode();
			if (statusCode != HttpStatus.SC_OK) {
				Log.w(getClass().getSimpleName(), "Error " + statusCode
						+ " for URL " + url);
			} else {
				HttpEntity getResponseEntity = getResponse.getEntity();
				InputStream source = getResponseEntity.getContent();

				Gson gson = new Gson();
				Reader reader = new InputStreamReader(source);
				ResponseItem responseItem = gson.fromJson(reader,
						ResponseItem.class);
				datas = responseItem.list;
				return OK;
			}
		} catch (IOException e) {
			getRequest.abort();
			Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
		}

		return ERROR;
	}

	@Override
	protected void onPostExecute(Integer result) {
		onRequestMediaListener.onRequestDone();
		if (result == OK) {
			start += datas.size();
			listener.onNewDataReceiver((ArrayList<MediaItem>) datas);
		} else {
			listener.onError();
		}
	}
}
